<!--成本管理弹出视图	-->
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <meta name="viewport" content="width=device-width" />
    <title>成本管理</title>
    <link href="~/Scripts/jquery-easyui/themes/bootstrap/easyui.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-easyui/jquery.min.js"></script>
    <script src="~/Scripts/jquery-easyui/jquery.easyui.min.js"></script>
    <script src="~/Scripts/jquery-easyui/locale/easyui-lang-zh_CN.js"></script>
    <link href="~/Content/themes/icon.css" rel="stylesheet" />
    <script src="~/Content/js/common.js"></script>  
    <link href="~/Content/themes/table.css" rel="stylesheet" />
    <link href="~/Content/formstyles.css" rel="stylesheet" />
    <script type="text/javascript"></script>
</head>
<body>

    <script type="text/javascript">
        //全局参数
        var ProjectID, ProjectNo, ProjectName;
        var IcmoNo;// row.IcmoNo,//关联主单号
        var FitemNo, FModel, FName;// row.FitemNo,//关联物料
        var entryid, worktype, parttype, classtype, price, weight, cost, estcost,budCost,stdCost,reaCost;
        var editIndex = undefined;
        //获取页面url参数
        function getQueryParam(name) {
            var obj = $("#ui_pm_cost_dialog").dialog('options');
            var queryParams = obj["queryParams"];
            return queryParams[name];
        }
        //初始化控件
        $(function () {
            ProjectID = getQueryParam("ProjectID");
            ProjectNo = getQueryParam("ProjectNo");
            ProjectName = getQueryParam("ProjectName");
            IcmoNo = getQueryParam("IcmoNo");
            FitemNo = getQueryParam("FitemNo");
            estcost = getQueryParam("estcost");
            budCost = getQueryParam("budCost");
            stdCost = getQueryParam("stdCost");
            reaCost = getQueryParam("reaCost");
            FName = getQueryParam("FName");
            FModel = getQueryParam("FModel");
            if (IcmoNo.length) {

            }
           // IcmoNo

            $("#tbICMOno").val(IcmoNo||ProjectNo);//若IcmoNo为空则默认主生产任务单号为项目编码！
            $("#tbFitemName").val(FName);//主物料名称
            $("#tbFModel").val(FModel);//主物料型号
            $('#ProjectNo').textbox({
                width: 200,
                label: '项目编码：',
                labelAlign: 'right',
                disabled: true,
                value: ProjectNo,
            }); 
            $('#ProjectName').textbox({
                width: 300,
                label: '项目名称：',
                labelAlign: 'right',
                disabled: true,
                value: ProjectName,
            });
            
            $('#tb_estCost').textbox({
                width: 200,
                label: '预估成本：',
                labelAlign: 'right',
                value: estcost,
            }); 
            $('#tb_budCost').textbox({
                width: 200,
                label: '预算成本：',
                labelAlign:'right',
                disabled: true,
                value: budCost,
            });
            $('#tbstdCost').textbox({
                width: 200,
                label: '标准成本：',
                labelAlign: 'right',
                disabled: true,
                value: stdCost,
            });
            $('#tbreaCost').textbox({
                width: 200,
                label: '实际成本：',
                labelAlign: 'right',
                disabled: true,
                value: reaCost,
            });
             
        });
 

        //单击其他行，判断是否结束编辑
        function endEditing() {
            if (editIndex == undefined) { return true }
            if ($('#dgYugu').datagrid('validateRow', editIndex)) {
                $('#dgYugu').datagrid('endEdit', editIndex);
                $('#dgYugu').datagrid('selectRow', editIndex); 
                calEstCost();
                $('#dgYugu').datagrid('acceptChanges');
                editIndex = undefined;
                //保存本行数据到数据库
                var row = $("#dgYugu").datagrid("getSelected");
              
                entryid = row.entryid;
                worktype = row.worktype;
                parttype = row.parttype;
                classtype = row.classtype;
                price = row.price;
                weight = row.weight;
                cost = row.cost;
      
                $.ajax({
                    url: "/PMCost/SaveEstCostEntry?r=" + Math.random(),
                    type: "post",
                    data: {
                        ProjectID: ProjectID,
                        entryid: row.entryid,
                        worktype: row.worktype,
                        parttype: row.parttype,
                        classtype: row.classtype,
                        price: row.price,
                        "weight": row.weight,
                        "cost": row.cost,
                        "totalcost": estCost
                    },
                    dataType: "json",
                    timeout: 5000,
                    success: function (data) {
                        if (data.success) {
                            $.show_alert("成功", "自动保存数据成功！");
                            editIndex = undefined;
                            //$("#ui_pm_edit_dialog").dialog('destroy');
                            $("#dgYugu").datagrid("reload");//重新加载数据;
                        } else {
                            $.show_alert("提示", data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (textStatus == "timeout") {
                            $.show_alert("提示", "请求超时，请刷新当前页重试！");
                        }
                        else {
                            $.show_alert("错误", textStatus + "：" + errorThrown);
                        }
                    }
                }); 
              
                return true;
            } else {
                setTimeout(function () {
                    $('#dgYugu').datagrid('selectRow', editIndex);//恢复选中编辑行！
                }, 0);
                //$('#dgYugu').datagrid('selectRow', editIndex);
                return false;
            }
        }
        //双击进入编辑状态；
        function onClickCell(index, field, value) {
            if (editIndex != index) {
                if (endEditing()) {
                    editIndex = index;
                    $('#dgYugu').datagrid('beginEdit', index);
                    //$('#dgYugu').datagrid('selectRow', index).datagrid('beginEdit', index);
                    var ed = $('#dgYugu').datagrid('getEditor', { index: index, field: field });
                    if (ed) {
                        ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
                    }
                   
                } else {
                    setTimeout(function () {
                        $('#dgYugu').datagrid('selectRow', editIndex);
                    }, 0);
                }
            }
          
        }
        function calEstCost() {
            estCost = 0;
            $('#tb_estCost').textbox('enable');
            var rows = $('#dgYugu').datagrid('getRows');
            for (var i = 0; i < rows.length; i++) {
                estCost += parseFloat(rows[i].cost);
            }
            $("#tb_estCost").textbox('setValue', estCost);
        }
        function onEndEdit(index, row) {           
           
          
        }
        //新增
        function append() {
            if (endEditing()) {
                $('#dgYugu').datagrid('appendRow', { status: 'P' });
                editIndex = $('#dgYugu').datagrid('getRows').length - 1;
                $('#dgYugu').datagrid('selectRow', editIndex)
                        .datagrid('beginEdit', editIndex);
            }
        }
        //删除
        function removeit() {
            if (editIndex == undefined) {
                $.show_alert("提示", "请先双击目标行，使其为编辑状态！");
                return;
            }
            var entryid = $('#dgYugu').datagrid('getRows')[editIndex].entryid;
            $('#dgYugu').datagrid('cancelEdit', editIndex)
                    .datagrid('deleteRow', editIndex);
            editIndex = undefined;
            if (entryid > 0) {
                //从服务器中更新数据
                calEstCost();
                $.ajax({
                    url: "/PMCost/SaveEstCostEntry?r=" + Math.random(),
                    type: "post",
                    data: {
                        ProjectID: ProjectID,
                        entryid: entryid,
                        method:'delete',
                        "totalcost": estCost
                    },
                    dataType: "json",
                    timeout: 5000,
                    success: function (data) {
                        if (data.success) {
                            $.show_alert("成功", "已从数据库删除该记录！");
                            $('#dgYugu').datagrid('acceptChanges');
                        } else {
                            $.show_alert("提示", data.msg);
                            $('#dgYugu').datagrid('rejectChanges');

                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (textStatus == "timeout") {
                            $.show_alert("提示", "请求超时，请刷新当前页重试！");
                        }
                        else {
                            $.show_alert("错误", textStatus + "：" + errorThrown);
                        }
                    }
                });

            }   

        }
        //手工保存
        function acceptit() {
            if (endEditing()) {
                editIndex == undefined;

                $('#dgYugu').datagrid('acceptChanges');
       
            } else {
                $.show_alert("提示", "没有按要求录入数据！");
            }
        }
        //撤销编辑
        function reject() {
            $('#dgYugu').datagrid('rejectChanges');
            editIndex = undefined;
        }
        //获取编辑内容
        function getChanges() {
            var rows = $('#dgYugu').datagrid('getChanges');
            alert(rows.length + ' rows are changed!');
        }
    
   
 
    $(function () {
        var editing; //判断用户是否处于编辑状态
        var flag;   //判断新增和修改方法
        $('#dgYugu').datagrid({
            idField: 'id',
            fitColumns: false,
            url: '/PMCost/getEstCostRows',
            queryParams: {
                ProjectID: ProjectID
               
            },
            striped: true,
            loadMsg: '数据正在加载,请耐心的等待...',
            rownumbers: true,
            singleSelect: true,
            collapsible: true,
            toolbar: '#tb',
            method: 'get',
            onDblClickRow: onClickCell,
            onClickCell: endEditing,
 
            onEndEdit: onEndEdit,

            //frozenColumns: [[
            //        { field: 'ck', checkbox: true }
            //]],

            columns: [[
                {
                    field: 'entryid',
                    title: '分录id',
                    hidden:true 
                },
                {
                    field: 'worktype',
                    title: '加工类别',
                    width: 80, 
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'codename',
                            textField: 'codename',
                            method: 'get',
                            url: '/Code/GetCodebyTypeId?typeid=1', 
                            required: true,
                            onChange:function(newValue,oldValue){
                                if (newValue != oldValue) {
                                    var row = $('#dgYugu').datagrid('getSelected');
                                    var rowIndex = $('#dgYugu').datagrid('getRowIndex', row);//获取行号
                                    //var thisTarget = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'worktype' }).target;
                                    //var value = thisTarget.combobox('getValue');
                                    var value = newValue;
                                    var target = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'parttype' }).target;
                                    var url = '/PMCost/getparttypelist?worktype=' + value;
                                    if (oldValue == null) { 
                                        //target.combobox('clear'); //清除原来的数据 
                                        target.combobox('reload', url);//联动下拉列表重载
                                    } else {
                                        target.combobox('clear'); //清除原来的数据 
                                        target.combobox('reload', url);//联动下拉列表重载
                                    } 
 
                                }
                            },
                            onSelect: function (data) {
                                
                            }
                        }
                    }
                },
                {
                    field: 'parttype',
                    title: '工件类别',
                    width: 80,
                    align: 'center',
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'codename',
                            textField: 'codename',
                            method: 'get',
                            required: true,
                            // url: '/Code/GetCodebyTypeId?typeid=1',
                            onChange: function (newValue, oldValue) {
                                if (newValue != oldValue) {
                                    var row = $('#dgYugu').datagrid('getSelected');
                                    var rowIndex = $('#dgYugu').datagrid('getRowIndex', row);//获取行号
                                    //var value = thisTarget.combobox('getValue');
                                    //var value = data.codename;
                                    var value = newValue;
                                    var target = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'classtype' }).target;
                                    // target.combobox('clear'); //清除原来的数据
                                    var url = '/PMCost/getclasstypelist?parttype=' + value;                                     
                                    if (oldValue == null) {                                        
                                        target.combobox('reload', url);//联动下拉列表重载
                                    } else {
                                        target.combobox('clear'); //清除原来的数据 
                                        target.combobox('reload', url);//联动下拉列表重载
                                    }
                                }
                            },
                            onSelect: function (data) {

                            }
                        }
                    }
                },
                 {
                     field: 'classtype',
                     title: '属性类别',
                     width: 160,
                     align: 'center',
                     formatter: function (value, row, index) {
                         if (value) {
                             return value.length > 10 ? '<span title="' + value + '">' + value + '</span>' : value;
                         } 
                     },
                     editor: {
                         type: 'combobox',
                         options: {
                             // url:'codeTypeAction_search.action?type=28',price
                             valueField: 'codename',
                             textField: 'codename',
                             onSelect: function (data) {
                                 var row = $('#dgYugu').datagrid('getSelected');
                                 var rowIndex = $('#dgYugu').datagrid('getRowIndex', row);//获取行号
                                 var thisTarget = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'price' }).target;
                                 thisTarget.val(data.price); //自动带入报价
                                 //重新计算价格
                                 var price = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'price' }).target.val();
                                 var weight = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'weight' }).target.val();
                                 var target = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'cost' }).target;
                                 var cost = parseFloat(price * weight).toFixed(2);
                                 console.log("属性调整：" + cost + "price:" + price + "weight:" + weight);
                                 target.val(cost);
                             }
                         }
                     }
                 },
                  {
                      field: 'price',
                      title: '计价标准',
                      width: 80,
                      align: 'center',
                      editor: {//允许修改价格
                          type: 'validatebox',
                          options: {
                              required: true,
                              precision: 2,
                              missingMessage: '计价标准必填!',
                              //onChange:
                              onValidate: function (data) {
                                  if (data) {
                                      var row = $('#dgYugu').datagrid('getSelected');
                                      var rowIndex = $('#dgYugu').datagrid('getRowIndex', row);//获取行号
                                      var price = $('#dgYugu').datagrid('getEditor', { 'index': editIndex, field: 'price' }).target.val();
                                      var weight = $('#dgYugu').datagrid('getEditor', { 'index': editIndex, field: 'weight' }).target.val();
                                      var target = $('#dgYugu').datagrid('getEditor', { 'index': editIndex, field: 'cost' }).target;
                                      
                                      var cost = parseFloat(price * weight).toFixed(2);
                                      console.log("计价调整：" + cost + "price:" + price + "weight:" + weight);
                                      target.val(cost);
                               
                                  }
                              }
                          }
                      }

                  },
                    {
                        field: 'weight',
                        title: '重量/KG',
                        width: 70,
                        align: 'center',
                        editor: {
                            type: 'validatebox',
                            options: {
                                required: true,
                                precision: 2,
                                missingMessage: '重量必填!',
                                onValidate: function (data) { 
                                    if (data) {                                      
                                        var price = $('#dgYugu').datagrid('getEditor', { 'index': editIndex, field: 'price' }).target.val();
                                        var weight = $('#dgYugu').datagrid('getEditor', { 'index': editIndex, field: 'weight' }).target.val();
                                        var target = $('#dgYugu').datagrid('getEditor', { 'index': editIndex, field: 'cost' }).target;
                                        var cost = parseFloat(price * weight).toFixed(2);
                                        console.log("重量调整：" + cost + "price:" + price + "weight:" + weight);
                                        target.val(cost);
                                    }
                                }
                                //onChange: function (newValue, oldValue) {
                                //    // alert("onChange" + newValue+";old:"+oldValue);
                                //    if (newValue > 0) {
                                //        var row = $('#dgYugu').datagrid('getSelected');
                                //        var rowIndex = $('#dgYugu').datagrid('getRowIndex', row);//获取行号
                                //        var price = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'price' }).target.val();
                                //        var weight = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'weight' }).target.val();
                                //        var target = $('#dgYugu').datagrid('getEditor', { 'index': rowIndex, field: 'cost' }).target;
                                //        var cost = price * weight;
                                //        console.log("重量调整：" + cost + "price:" + price + "weight:" + weight);
                                //        target.val(cost);
                                //        //target.textbox('setValue', cost);//自动计算成本
                                //    }
                                //}
                            }
                        }
                    },
                      {
                          field: 'cost',
                          title: '计价/元',
                          width: 80,
                          align: 'center',
                          editor: {
                              type: 'validatebox',
                              options: {
                                  required: true,
                                  precision:2,
                                  missingMessage: '成本计价必填!'
                              }
                          }
                      } 
            ]]
        });
    });


        //标准成本
    $(function () {
        //tab页内
        $('#tbFitem').textbox({
            buttonText: '查找',
            buttonAlign: 'right',
            iconCls: 'icon-search',
            iconAlign: 'right',
            label: '物料编码:',
            value:FitemNo,
            onClickButton: function () {
                console.log("button clicked!");
                $("#div_biaozhun_dd").dialog({
                    id: "ui_pm_cost_choiceFitem_dialog",
                    href: "/Bom/FitemSearchModel",
                    title: "查找物料",
                    height: 500,
                    width: 600,
                    modal: true, 
                    toolbar: [],
                    buttons: [{
                        id: "ui_pm_cost_choiceFitem_btn",
                        text: '确定',
                        handler: function () {
                            $('#ui_pm_cost_choiceFitem_btn').linkbutton('disable'); 
                            var row = $("#ui_fitem_dg").datagrid("getSelected");
                            if (row == null) {
                                $.show_alert("提示", "请先勾选项目");
                                return;
                            }
                            if (row.length > 1) {
                                $.show_alert("提示", "不支持批量处理项目");
                                $("#ui_fitem_dg").datagrid('clearSelections').datagrid('clearChecked');
                                return;
                            }
                            
                            if (row.FstandardCost > 0) {
                                stdCost = row.FstandardCost + row.FstandardManHour * 20;
                            } else {
                                stdCost = row.ForderPrice;
                            }
                            if (stdCost>90000000 || stdCost<0) {
                                $.show_alert("提示", "成本数据计算结果异常：" + stdCost);
                                return;
                            }

                            $("#tbFitem").textbox('setText',row.FItemID);
                            $("#tbFitemName").val(row.FName);
                            $("#tbFModel").val( row.FModel);
                            $("#tbstdCost").textbox('setText', stdCost);
                            //$.show_alert("标准成本", stanCost);
                            $("#ui_pm_cost_choiceFitem_dialog").dialog('destroy');  //销毁dialog对象
                            $("#div_biaozhun_dd2").append("<div id='div_biaozhun_dd'></div>");//添加容器
                            //ajax存储标准成本
                            //return;
                            $.ajax({
                                url: "/PMCost/SaveStdCostEntry?r=" + Math.random(),
                                type: "post",
                                data: {
                                    ProjectID: ProjectID,
                                    FitemNo: row.FItemID,
                                    FName: row.FName,
                                    FModel:row.FModel,
                                    "stdCost": stdCost
                                },
                                dataType: "json",
                                timeout: 5000,
                                success: function (data) {
                                    if (data.success) {
                                        //$.show_alert("成功", "自动保存数据成功！");
                                        //editIndex = undefined;
                                        ////$("#ui_pm_edit_dialog").dialog('destroy');
                                        //$("#dgYugu").datagrid("reload");//重新加载数据;
                                    } else {
                                        $.show_alert("提示", data.msg);
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    if (textStatus == "timeout") {
                                        $.show_alert("提示", "请求超时，请刷新当前页重试！");
                                    }
                                    else {
                                        $.show_alert("错误", textStatus + "：" + errorThrown);
                                    }
                                }
                            });
                        }
                    }],
                    onClose: function () {
                        $("#ui_pm_cost_choiceFitem_dialog").dialog('destroy');  //销毁dialog对象
                        $("#div_biaozhun_dd2").append("<div id='div_biaozhun_dd'></div>");//添加容器

                    }

                })                
            }, 
        })

    }) 

        //实际成本
    function calReaCost() {
        var ficmono = $("#tbICMOno").val();
        $.ajax({
            url: "/PMCost/SaveReaCostEntry?r=" + Math.random(),
            type: "post",
            data: {
                ProjectID: ProjectID,
                "ficmono": ficmono,
                ProjectNo: ProjectNo
            },
            dataType: "json",
            timeout: 5000,
            success: function (data) {
                if (data.success) {
                    $("#tbreaCost").textbox('setText', data.msg);
                    $.show_alert("成功", "实际成本为："+data.msg); 
                } else {
                    $.show_alert("提示", data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (textStatus == "timeout") {
                    $.show_alert("提示", "请求超时，请刷新当前页重试！");
                }
                else {
                    $.show_alert("错误", textStatus + "：" + errorThrown);
                }
            }
        });
    }

    </script>

 
    <div style="text-align:left" >
        <input type="hidden" name="ProjectID" id="ProjectID" />
        <input id="ProjectNo" type="text" style="width:120px">
        <input class="easyui-textbox" name="ProjectName" id="ProjectName" data-options="disabled:true" />
    </div> 
    <div style="text-align:left">
        <input id="tb_estCost" type="text" style="width:120px">
        <input id="tb_budCost" type="text" style="width:120px">
        <input id="tbstdCost" type="text" style="width:120px">
        <input id="tbreaCost" type="text" style="width:120px">
    </div>
      <div id="tt_cost" class="easyui-tabs" style=" padding:3px; ">
            <div id="div_yugu" title="预估成本">            
                <table id="dgYugu"   style=" width:600px;height:200px"></table> 
                <div id="tb" style="height:auto">
                    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" onclick="append()">添加</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="removeit()">删除</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true" onclick="acceptit()">保存</a>
                    <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-undo',plain:true" onclick="reject()">取消</a>
                    @*<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true" onclick="getChanges()">GetChanges</a>*@
                </div>

                <div >提示：如需修改数据，请双击行进入编辑状态。</div>
                </div>
            <div id="div_yusuan" title="预算成本">  </div>
         <!--   <div id="div_biaozhun" title="标准成本"> 
                <br>
                 <input id="tbFitem" type="text" style="width:350px"><br>
                物料名称：<input id="tbFitemName" type="text" style="width:300px"><br>
                规格型号：<input id="tbFModel" type="text" style="width:300px"> 

                <div id="div_biaozhun_dd"></div>
                <div id="div_biaozhun_dd2"></div>
            </div> -->
            <div id="div_shiji" title="实际成本">
                <br>                 
                主生产任务单号：<input id="tbICMOno" type="text" style="width:300px"><br>
                <a href="javascript:void(0)" class="easyui-linkbutton" onclick="calReaCost()">计算实际成本</a> 
                <br>  说明：填写或检查主生产任务单号，点击‘计算’。
            </div> 

</div>
 
</body>
</html>
